package com.xuanyuanxinyu.func.gilde;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.ResourceDecoder;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.resource.SimpleResource;
import com.caverock.androidsvg.SVG;
import com.caverock.androidsvg.SVGParseException;

import java.io.IOException;
import java.io.InputStream;

/**
 * SVG图片计算
 * @author tanzh
 */
public class SvgDecoder implements ResourceDecoder<InputStream, SVG> {
    private final SVGParser mSvgParser = new SVGParser();

    @Override
    public boolean handles(@NonNull InputStream source, @NonNull Options options) throws IOException {
        // 只处理 SVG 格式的图片
        return true;
    }

    @Nullable
    @Override
    public Resource<SVG> decode(@NonNull InputStream source, int width, int height, @NonNull Options options)
            throws IOException {
        SVG svg = null;
        try {
            svg = mSvgParser.parseFromInputStream(source);
        } catch (SVGParseException e) {
            e.printStackTrace();
        }
        return new SimpleResource<>(svg);
    }

    private static class SVGParser {

        private SVG parseFromInputStream(InputStream inputStream)
                throws SVGParseException {
            try {
                SVG svg = SVG.getFromInputStream(inputStream);
                // 强制转换为指定宽度和高度的尺寸，以便后续的图片处理
                svg.setDocumentWidth(PictureDrawableUtils.MAX_SCALE_FACTOR);
                svg.setDocumentHeight(PictureDrawableUtils.MAX_SCALE_FACTOR);
                return svg;
            } catch (SVGParseException ex) {
                throw ex;
            }
        }
    }
}
